package com.sm.healthy.utils;

import android.serialport.api.SerialPort;
import android.util.Log;

import com.sm.healthy.event.SerialPortDataMsgEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * Created by Administrator on 2017/6/6.
 * todo 合适的地方打开串口
 */

public class SerialPortUtil {

    public final static String ACTION_SERIAPORT_READ = "SeriaPort.ACTION_SERIAPORT_READ";
    public static SerialPort serialPort = null;
    public static InputStream inputStream = null;
    public static OutputStream outputStream = null;

    public static Thread receiveThread = null;

    public static boolean flag = false;


    public static void openSrialPort(){
        try {
            Log.e("csw", "openSrialPort: 打开串口");
            serialPort = new SerialPort(new File("/dev/"+ IConstant.PORT), IConstant.BAUDRATE,666);
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            flag = true;
            receiveSerialPort();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeSerialPort(){
        try {
            if(inputStream != null) {
                inputStream.close();
            }
            if(outputStream != null){
                outputStream.close();
            }
            flag = false;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void sendSerialPort(byte[] data){
        try {
            outputStream.write(data);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     */
    public static void receiveSerialPort(){
        if(receiveThread != null)
            return;

        receiveThread = new Thread(){
            @Override
            public void run() {
                this.setPriority(Thread.MAX_PRIORITY);
                while (flag) {
                    try {
                        byte[] readData = new byte[1024];
                        if (inputStream == null) {
                            return;
                        }
                        int size = inputStream.read(readData);

                        if (size>0 && flag) {
                            EventBus.getDefault().post(new SerialPortDataMsgEvent(ACTION_SERIAPORT_READ,readData,size));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        receiveThread.start();
    }

}
